
# David Beal <david.beal@gmail.com>

import vim
import os
class nav(object):
	code_map=\
	[
		[['c','cc','cpp'],['h']],
	]
	@staticmethod
	def find_alternative(map_index):
		name=vim.current.buffer.name
		#print 'name '+str(name)
		spl=name.split('.')
		#print 'spl '+str(spl)
		base='.'.join(spl[:-1])
		ext=spl[-1]
		#print 'base '+str(base)
		#print 'ext '+str(ext)
		dst=False
		for map in nav.code_map:
			s=map_index
			d=s^1
			for se in map[s]:
				if se==ext:
					#print 'found source extension '+str(se)
					#print 'source list '+str(map[s])
					#print 'header list '+str(map[d])
					##print 'se '+str(se)
					for he in map[d]:
						try_header=base+'.'+he
						if nav.exists(try_header):
							dst=try_header
					if not dst:
						# use first alternative
						dst=base+'.'+map[d][0]

		if dst:
			#path='foo.txt'
			#vim.current.buffer.name='foo.txt'
			#vim.current.file
			#print 'dst '+str(dst)
			#dst=name
			#print 'exists '+str(nav.exists(dst))
			vim.command('e '+str(dst))
	@staticmethod
	def find_header():
		nav.find_alternative(0)
	@staticmethod
	def find_source():
		nav.find_alternative(1)
	@staticmethod
	def exists(path):
		result=False
		try:
			os.stat(path)
			result=True
		except Exception,e:
			#print 'e '+str(e)
			pass
		return result

